<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--    监听一个输入框，文字变化后触发change事件-->
<!--    直接用keyup之间，则会频发change事件-->
<!--    防抖：用户输入结束或暂停时，才会触发change事件-->
<input type="text" id="input1">
</body>
<script>
  const input1 = document.getElementById('input1')
  // let timer = null
  // input1.addEventListener('keyup', function () {
  //   if (timer) {
  //     clearTimeout(timer)
  //   }
  //   timer = setTimeout(() => {
  //     //模拟触发change事件
  //     console.log(input1.value)
  //     //清空定时器
  //     timer = null
  //   }, 500)
  // })
  function debounce(fn, delay = 500) {
    let timer = null
    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        //为了使函数的参数和this正确
        fn.apply(this, arguments)
        timer = null
      }, delay)
    }
  }

  input1.addEventListener('keyup', debounce(function () {
    console.log(input1.value)
  }, 600))
</script>
</html>
